//
//  Common.m
//  LBBase
//
//  Created by Gary on 15/7/1.
//  Copyright (c) 2015年 Lebo. All rights reserved.
//

#import "Common.h"
#import "FileIO.h"
#import "CommonDefine.h"
#import "ConfigDefine.h"
#import "ModuleDefine.h"
#import "BusinessFramework.h"
#import "NYXImagesKit.h"
#import "AFNetworking.h"
#import "LBModalViewController.h"
#import "UIView+Toast.h"
#import "UIViewController+BaseBusiness.h"
#import "LoginViewController.h"
#import "NSAttributedString+HTML.h"
#import "NSJSONSerialization+RemovingNulls.h"
#import <CommonCrypto/CommonDigest.h>

static const CGFloat kHtmlTextFontSize         = 15.f;

@implementation Common

+ (ESystemVersion)systemVersion {
    static ESystemVersion sysVersion = -1;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        NSString *version = [UIDevice currentDevice].systemVersion;
        NSUInteger intVer = [[version componentsSeparatedByString:@"."][0] intValue];
        NSString *str;
        if (intVer <= 6) {
            sysVersion = ESystemVersion6OrLess;
            str = @"IOS 6 or early";
        } else if (intVer == 7) {
            sysVersion = ESystemVersion7;
            str = @"IOS 7";
        } else {
            sysVersion = ESystemVersion8OrGreater;
            str = @"IOS 8 or later";
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            LogInfo(@"Current system version: %@", str);
        });
    });
    
    return sysVersion;
}

+ (EScreenScaleType)screenScale {
    static EScreenScaleType screenScl = -1;
    static dispatch_once_t onceToken;
    
    //#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
    
    dispatch_once(&onceToken, ^{
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            screenScl = EScreenScaleIPad;
        } else if ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO) {
            screenScl = EScreenScaleIPhone4;
        } else if ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO) {
            screenScl = EScreenScaleIPhone6;
        } else if ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO) {
            screenScl = EScreenScaleIPhone6P;
        } else if ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO) {
            screenScl = EScreenScaleIPad;
        } else {
            screenScl = EScreenScaleIPhone4;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            LogInfo(@"Current screen size: %f, %f", [[UIScreen mainScreen] currentMode].size.width, [[UIScreen mainScreen] currentMode].size.height);
            LogInfo(@"Current screen scale: %d", screenScl);
        });
    });
    
    return screenScl;
}

+ (BOOL)isInstallApp:(NSString *)urlStr{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlStr]] ;
}

+ (void)openApp:(NSString *)urlStr{
    if ([Common isInstallApp:urlStr]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }
}

+ (UIViewController*)currentViewController {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    for (UIView* next = [window superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

__weak static UIViewController *rootViewController = nil;

+ (UIViewController*)rootViewController {
    return rootViewController;
}

+ (void)setRootViewController:(UIViewController*)root {
    rootViewController = root;
}

+ (UIViewController*)viewController:(NSString*)identifier {
    UIStoryboard* homeStoryboard = [UIStoryboard storyboardWithName:@"Home"
                                                             bundle:[NSBundle mainBundle]];
    return [homeStoryboard instantiateViewControllerWithIdentifier:identifier];
}

+ (UIViewController*)viewController:(NSString*)identifier storyboard:(NSString*)storyboard {
    UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:[Common isEmptyString:storyboard] ? @"Home" : storyboard
                                                             bundle:[NSBundle mainBundle]];
    return mainStoryboard ? [mainStoryboard instantiateViewControllerWithIdentifier:identifier] : nil;
}

+ (void)presentModalViewController:(UIViewController *)root animated:(BOOL)flag completion:(void (^)(void))completion {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    LBModalViewController *nav = [[LBModalViewController alloc] initWithRootViewController:root];
    [delegate.window.rootViewController presentViewController:nav animated:flag completion:completion];
}

+ (NSString*)getLocalStr:(NSString*)key {
    return key ? NSLocalizedStringFromTable(key, @"Localizable", nil) : key;
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size {
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

+ (void)printFrame:(UIView*)view message:(NSString*)msg {
    NSLog(@"%@, x: %f, y: %f, width: %f, height: %f", msg, view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
}

+ (CGSize)fitSizeForText:(NSString*)text font:(UIFont*)font {
    return [Common fitSizeForText:text font:font maxWidth:kUnknownWidth maxHight:kUnknownHeight];
}

+ (CGSize)fitSizeForText:(NSString*)text font:(UIFont*)font maxWidth:(CGFloat)maxWidth {
    return [Common fitSizeForText:text font:font maxWidth:maxWidth maxHight:kUnknownHeight];
}

+ (CGSize)fitSizeForText:(NSString*)text font:(UIFont*)font maxHight:(CGFloat)maxHeight {
    return [Common fitSizeForText:text font:font maxWidth:kUnknownWidth maxHight:maxHeight];
}

+ (CGSize)fitSizeForText:(NSString*)text font:(UIFont*)font maxWidth:(CGFloat)maxWidth maxHight:(CGFloat)maxHeight {
    //return [text sizeWithFont:font constrainedToSize:CGSizeMake(maxWidth,maxHeight) lineBreakMode:NSLineBreakByWordWrapping];
    return [text boundingRectWithSize:CGSizeMake(maxWidth,maxHeight)
                              options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                           attributes:@{NSFontAttributeName:font}
                              context:nil].size;
}

+ (void)networkReachabilityStartMonitoring:(void (^)(NSInteger status))block {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager stopMonitoring];
    [manager setReachabilityStatusChangeBlock:nil];
    [manager startMonitoring];  //开启网络监视器；
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (block) {
            block(status);
        }
    }];
}

+ (NSString*)URLEncodedStringFromKeyAndValue:(NSString*)key value:(id)value {
    NSMutableArray *mutablePairs = [NSMutableArray array];
    for (NSDictionary *dic in [Common queryStringPairsFromKeyAndValue:key value:value]) {
        id fieldInPair = [dic objectForKey:@"field"];
        id valueInPair = [dic objectForKey:@"value"];
        if (valueInPair && ![valueInPair isEqual:[NSNull null]]) {
            NSString *fieldEncoding = (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)fieldInPair, (__bridge CFStringRef) @"[].", (__bridge CFStringRef)@":/?&=;+!@#$()',*", CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
            NSString *valueEncoding = (__bridge_transfer  NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)valueInPair, (__bridge CFStringRef) @"[].", (__bridge CFStringRef)@":/?&=;+!@#$()',*", CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
            
            [mutablePairs addObject:[NSString stringWithFormat:@"%@=%@", fieldEncoding, valueEncoding]];
        }
    }
    
    return [mutablePairs componentsJoinedByString:@"&"];
}

+ (NSArray*)queryStringPairsFromKeyAndValue:(NSString*)key value:(id)value {
    NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
    
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description"
                                                                     ascending:YES
                                                                      selector:@selector(compare:)];
    if ([value isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dictionary = value;
        // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
        for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            id nestedValue = [dictionary objectForKey:nestedKey];
            if (nestedValue) {
                [mutableQueryStringComponents addObjectsFromArray:[Common queryStringPairsFromKeyAndValue:(key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey) value:nestedValue]];
            }
        }
    } else if ([value isKindOfClass:[NSArray class]]) {
        NSArray *array = value;
        for (id nestedValue in array) {
            [mutableQueryStringComponents addObjectsFromArray:[Common queryStringPairsFromKeyAndValue:[NSString stringWithFormat:@"%@[]", key] value:nestedValue]];
        }
    } else if ([value isKindOfClass:[NSSet class]]) {
        NSSet *set = value;
        for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            [mutableQueryStringComponents addObjectsFromArray:[Common queryStringPairsFromKeyAndValue:key value:obj]];
        }
    } else {
        [mutableQueryStringComponents addObject:[NSDictionary dictionaryWithObjectsAndKeys:value, @"value", key, @"field", nil]];
    }
    
    return mutableQueryStringComponents;
}

+ (NSDictionary*)parametersFromURLString:(NSString*)urlString {
    //获取问号的位置，问号后是参数列表
    NSRange range = [urlString rangeOfString:@"?"];
    
    //获取参数列表
    NSString *propertys = [urlString substringFromIndex:(int)(range.location+1)];
    
    //进行字符串的拆分，通过&来拆分，把每个参数分开
    NSArray *arr = [propertys componentsSeparatedByString:@"&"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (NSString *paramStr in arr) {
        NSArray *component = [paramStr componentsSeparatedByString:@"="];
        if (component.count > 1) {
            dic[component[0]] = component[1];
        }
    }
    
    return [NSDictionary dictionaryWithDictionary:dic];
}

+ (NSInteger)dataListPageSize {
    static NSInteger dataListPageSize = 7;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        if (EScreenScaleIPhone4 == [Common screenScale]) {
            dataListPageSize = 6;
        }
    });
    
    return dataListPageSize;
}

+ (void)downloadInAppStore:(const NSString*)appId {
    NSString *link = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@&mt=8", appId];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:link]];
}

+ (void)callServicePhone {
    NSString *phoneNum = [kServicePhoneNumber stringByReplacingOccurrencesOfString:@"-" withString:kEmptyString];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNum]]];
}

+ (NSMutableAttributedString*)attrStrFromHtmlText:(NSString*)htmlText {
    return [[NSMutableAttributedString alloc] initWithHTMLData:[htmlText dataUsingEncoding:NSUTF8StringEncoding]
                                            documentAttributes:NULL];
}

+ (NSAttributedString*)attrStrFromHtmlText:(NSString *)htmlText font:(UIFont *)font {
    NSMutableAttributedString *attrStr = [Common attrStrFromHtmlText:htmlText];
    if (font) {
        [attrStr addAttributes:@{NSFontAttributeName: font}
                         range:NSMakeRange(0, attrStr.length)];
    } else {
        [attrStr addAttributes:@{NSFontAttributeName: MakeFont(kHtmlTextFontSize)}
                         range:NSMakeRange(0, attrStr.length)];
    }
    return attrStr;
}

+ (NSAttributedString *)getAttributedString:(NSString *)desString{
    NSString *fontString1 = @"<font color=red>";
    NSString *fontString2 = @"</font>";
    NSRange range1 = [desString rangeOfString:fontString1];
    desString = [desString stringByReplacingOccurrencesOfString:fontString1 withString:@""];
    NSRange range2 = [desString rangeOfString:fontString2];
    desString = [desString stringByReplacingOccurrencesOfString:fontString2 withString:@""];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:desString];
    [attributedStr addAttribute:NSFontAttributeName
                          value:[UIFont systemFontOfSize:14.0]
                          range:NSMakeRange(range1.location, range2.location-range1.location)];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[UIColor redColor]
                          range:NSMakeRange(range1.location, range2.location-range1.location)];
    return attributedStr;
}

+ (NSString *)textRemovedHtmlTag:(NSString *)htmlText {
    if ([Common isEmptyString:htmlText]) {
        return kEmptyString;
    }
    
    htmlText = [htmlText stringByReplacingOccurrencesOfString:@"\\r" withString:@""];
    NSScanner *scanner = [NSScanner scannerWithString:htmlText];
    NSString *text = nil;
    while ([scanner isAtEnd] == NO) {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        htmlText = [htmlText stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text]
                                                       withString:@""];
    }
    NSString *retText = [htmlText stringByReplacingOccurrencesOfString:@"<([^>]*)>" withString:@""];
    retText = [retText stringByReplacingOccurrencesOfString:@"&nbsp" withString:@" "];
    retText = [retText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return retText;
}

+ (NSDate*)dateFromString:(NSString*)string {
    return [Common dateFromString:string format:kDateTimeFormatDefault];
}

+ (NSDate*)dateFromString:(NSString*)string format:(NSString*)format {
    if ([Common isEmptyString:string]) {
        return nil;
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    return [formatter dateFromString:string];
}

+ (NSString*)formatTimeString:(NSUInteger)hours minutes:(NSUInteger)minutes seconds:(NSUInteger)seconds {
    return [NSString stringWithFormat:@"%@:%@:%@", [Common fullDecimal:hours], [Common fullDecimal:minutes], [Common fullDecimal:seconds]];
}

//补足到十位数
+ (NSString*)fullDecimal:(NSUInteger)digital {
    if (digital <= 9) {
        return [NSString stringWithFormat:@"0%lu", (unsigned long)digital];
    }
    return [NSString stringWithFormat:@"%lu", (unsigned long)digital];
}

+ (BOOL)copyResourceToDocumentsFolder:(NSString*)fileName {
    NSString *name = [fileName stringByDeletingPathExtension];
    NSString *ext = [fileName pathExtension];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:name ofType:ext];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:filePath]) {
        BOOL isDir = NO;
        if ([fm fileExistsAtPath:kResourceDirectory isDirectory:&isDir]) {
            if (!isDir) {
                //删除已有同名的文件
                if (isDir && ![fm removeItemAtPath:kResourceDirectory error:nil]) {
                    LogError(@"delete file fail: %@", kResourceDirectory);
                    return NO;
                }
                //重新创建文件夹
                if (![fm createDirectoryAtPath:kResourceDirectory withIntermediateDirectories:YES attributes:nil error:nil]) {
                    LogError(@"create directory fail: %@", kResourceDirectory);
                    return NO;
                }
            }
        } else {
            //创建文件夹
            if (![fm createDirectoryAtPath:kResourceDirectory withIntermediateDirectories:YES attributes:nil error:nil]) {
                LogError(@"create directory fail: %@", kResourceDirectory);
                return NO;
            }
        }
        
        //目标文件路径
        NSString *desFilePath = [kResourceDirectory stringByAppendingPathComponent:fileName];
        if ([fm fileExistsAtPath:desFilePath]) {
            //若存在，先删除
            NSError *error = nil;
            if (![fm removeItemAtPath:desFilePath error:&error]) {
                LogError(@"move file fail: %@, error: %@", desFilePath, error.description);
                return NO;
            }
        }
        
        //转移文件到外层，便于查看
        NSError *error = nil;
        if (![fm copyItemAtPath:filePath toPath:desFilePath error:&error]) {
            LogError(@"move file fail: %@, error: %@", filePath, error.description);
            return NO;
        }
    }
    
    return YES;
}

+ (NSString*)getResourceFilePath:(NSString*)fileName {
    if ([Common copyResourceToDocumentsFolder:fileName]) {
        return [kResourceDirectory stringByAppendingPathComponent:fileName];
    }
    
    return nil;
}

+ (long long)fileSizeAtPath:(NSString*) filePath {
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

+ (NSString*)trim:(NSString*)string {
    if (!string) {
        return nil;
    }
    
    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

+ (BOOL)isEmptyString:(NSString*)string {
    if (!IsEmpty(string)) {
        if (![[Common trim:string] isEqualToString:@""]) {
            return NO;
        }
    }
    
    return YES;
}

+ (NSString *)md5:(NSString*)string {
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest );
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02X", digest[i]];
    
    return output;
}

+ (BOOL)regexString:(NSString*)string match:(NSString*)match {
    NSPredicate *regex = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", match];
    if ([regex evaluateWithObject:string]) {
        return YES;
    }
    
    return NO;
}

+ (BOOL)isChinaMobileNumber:(NSString *)string {
    return [Common regexString:string match:@"^\\+?(86)?1\\d{10}$"];
}

+ (BOOL)isAccount:(NSString*)string {
    //return [Common regexString:string match:@"^\\w{6,16}$"];
    return [Common regexString:string match:@"^\\w{1,16}$"];
}

+ (BOOL)isPassword:(NSString*)string {
    //return [Common regexString:string match:@"^\\w{6,14}$"];
#ifdef RUN_IN_PRODUCTION_ENV
    return [Common regexString:string match:@"^\\w{6,20}$"];
#else
    return [Common regexString:string match:@"^\\w{1,20}$"];
#endif
}

+ (BOOL)isRealName:(NSString*)string {
    return [Common regexString:string match:@"^[\\u4e00-\\u9fa5A-Za-z0-9_]{4,20}$"];
}

+ (BOOL)isIDNumber:(NSString*)string {
    return [Common regexString:string match:@"^[0-9Xx]{15}$"] || [Common regexString:string match:@"^[0-9Xx]{18}$"];
}

+ (BOOL)isValidateEmail:(NSString *)string {
    return [Common regexString:string match:@"[A-Z0-9a-z_%]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"];
}

static NSNumber *isProductionEnv = nil;

+ (BOOL)isProductionEnv {
#ifdef RUN_IN_PRODUCTION_ENV
    return YES;
#else
    if (isProductionEnv) {
        return isProductionEnv.boolValue;
    }
    
    isProductionEnv = [[NSUserDefaults standardUserDefaults] objectForKey:kUSKeyIsProductionEnv];
    if (isProductionEnv && [isProductionEnv boolValue]) {
        return YES;
    }
    isProductionEnv = @(NO);
    return NO;
#endif
}

+ (void)updateProductionEnv:(BOOL)isProEnv {
#ifdef RUN_IN_PRODUCTION_ENV
    return;
#else
    isProductionEnv = @(isProEnv);
    [[NSUserDefaults standardUserDefaults] setObject:isProductionEnv forKey:kUSKeyIsProductionEnv];
    LogInfo(@"Current running environment: %@", isProEnv ? @"Production" : @"Test");
#endif
}

static NSNumber *isPaymentProductionEnv = nil;

+ (BOOL)isPaymentProductionEnv {
    if ([Common isProductionEnv]) {
        return YES;
    }
    
    if (isPaymentProductionEnv) {
        return isPaymentProductionEnv.boolValue;
    }
    
    isPaymentProductionEnv = [[NSUserDefaults standardUserDefaults] objectForKey:kUSKeyIsPaymentProductionEnv];
    if (isPaymentProductionEnv && [isPaymentProductionEnv boolValue]) {
        return YES;
    } else {
#ifdef RUN_IN_PAY_PRODUCTION_ENV
        isPaymentProductionEnv = @(YES);
        return YES;
#else
        isPaymentProductionEnv = @(NO);
        return NO;
#endif
    }
}

+ (void)updatePaymentProductionEnv:(BOOL)isProEnv {
#ifdef RUN_IN_PRODUCTION_ENV
    return;
#else
    isPaymentProductionEnv = @(isProEnv);
    [[NSUserDefaults standardUserDefaults] setObject:isPaymentProductionEnv forKey:kUSKeyIsPaymentProductionEnv];
    LogInfo(@"Current payment environment: %@", isProEnv ? @"Production" : @"Test");
#endif
}

static NSString *baseServerURL = nil;

+ (NSString*)baseServerURL {
    if ([Common isProductionEnv]) {
        if (!baseServerURL) {
            baseServerURL = [NSString stringWithFormat:@"%@", kBaseServerURLProduction];
        }
        return baseServerURL;
    }
    
    if (!baseServerURL) {
        NSString *url = [[NSUserDefaults standardUserDefaults] objectForKey:kUSKeyBaseServerURL];
        if (![Common isEmptyString:url]) {
            baseServerURL = url;
        } else {
            baseServerURL = [NSString stringWithFormat:@"%@", kBaseServerURL];
        }
        LogInfo(@"Current base server url: %@", baseServerURL);
    }
    
    return baseServerURL;
}

+ (void)updateBaseServerURL:(NSString*)url save:(BOOL)save {
    if (![Common isEmptyString:url]) {
        baseServerURL = url;
        if (save) {
            [[NSUserDefaults standardUserDefaults] setObject:baseServerURL forKey:kUSKeyBaseServerURL];
        }
        LogInfo(@"Current base server url is updated: %@", baseServerURL);
    }
}

+ (void)loginWithCurrentUser {
    LogFunc;
    //    NSString *currentUserName = [Common currentUserName];
    //    NSString *currentPassword = [Common currentPassword];
    //    NSArray *arr = [NSArray arrayWithObjects:currentUserName, currentPassword, nil];
    //    [BF callBusinessProcess:MakeID(ELoginManager, ELoginLogin) withInParam:arr];
}

static NSString *deviceToken = nil;

+ (NSString*)currentDeivceToken {
    if (!deviceToken) {
        deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:kUSKeyCurrentDeviceToken];
        if (!deviceToken) {
            deviceToken = @"";
        }
    }
    return deviceToken;
}

+ (void)updateDeivceToken:(NSString*)str {
    if (str) {
        deviceToken = token = [NSString stringWithString:str];
        [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:kUSKeyCurrentDeviceToken];
    }
}

static NSString *token = nil;

+ (NSString*)currentToken {
    if (!token) {
        token = [[NSUserDefaults standardUserDefaults] objectForKey:kUSKeyCurrentToken];
        if (!token) {
            token = @"";
        }
    }
    return token;
}

+ (void)updateToken:(NSString*)str {
    if (str) {
        token = [NSString stringWithString:str];
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:kUSKeyCurrentToken];
    }
}

static NSString *userID = nil;

+ (NSString*)currentUserID {
    if (!userID) {
        userID = [[NSUserDefaults standardUserDefaults] objectForKey:kUSKeyCurrentUserID];
        if (!userID) {
            //userID = @"current";
        }
    }
    return userID;
}

+ (void)updateUserID:(NSString*)str {
    if (str) {
        userID = [NSString stringWithString:str];
        [[NSUserDefaults standardUserDefaults] setObject:userID forKey:kUSKeyCurrentUserID];
    }
}

+ (NSDictionary*)currentUserInfo {
    return [[NSUserDefaults standardUserDefaults] objectForKey:kUSKeyCurrentUserInfo];
}

+ (void)showLocalMessage:(NSString *)message {
    [Common showAlert:[Common getLocalStr:@"CommonTitlePrompt"] message:[Common getLocalStr:message]];
}

+ (void)showLocalAlert:(NSString*)title message:(NSString*)message {
    [Common showAlert:[Common getLocalStr:title] message:[Common getLocalStr:message]];
}

+ (void)showLocalAlert:(NSString *)title
               message:(NSString *)message
              delegate:(id<UIAlertViewDelegate>)delegate {
    [Common showAlert:[Common getLocalStr:title]
              message:[Common getLocalStr:message]
             delegate:delegate
                  tag:0];
}

+ (void)showLocalAlert:(NSString*)localTitle message:(NSString*)localMessage tag:(NSInteger)tag {
    [Common showAlert:[Common getLocalStr:localTitle]
              message:[Common getLocalStr:localMessage]
             delegate:nil
                  tag:tag];
}

+ (void)showLocalAlert:(NSString *)localTitle
               message:(NSString *)localMessage
              delegate:(id<UIAlertViewDelegate>)delegate
                   tag:(NSInteger)tag {
    [Common showAlert:[Common getLocalStr:localTitle]
              message:[Common getLocalStr:localMessage]
             delegate:delegate
                  tag:tag];
}

+ (void)showMessage:(NSString*)message {
    [Common showAlert:[Common getLocalStr:@"CommonTitlePrompt"] message:message];
}

+ (void)showAlert:(NSString*)title message:(NSString*)message {
    [Common showAlert:title message:message delegate:nil tag:kIntegerInvalid];
}

+ (void)showAlert:(NSString*)title
          message:(NSString *)message
         delegate:(id<UIAlertViewDelegate>)delegate
              tag:(NSInteger)tag {
    UIAlertView *alert =
    [[UIAlertView alloc] initWithTitle:title
                               message:message
                              delegate:delegate
                     cancelButtonTitle:[Common getLocalStr:@"CommonTitleConfirm"]
                     otherButtonTitles:nil, nil];
    if (tag > 0) {
        alert.tag = tag;
    }
    
    [alert show];
}

+ (void)showCustomerAlert:(UIView *)view {
    [Common showCustomerAlert:view showCloseButton:YES];
}

+ (void)showCustomerAlert:(UIView *)view showCloseButton:(BOOL)showCloseButton {
    if (view) {
        [CAlert addViewToCenter:view];
        if (showCloseButton) {
            [CAlert showCloseButton];
        }
        [[[UIApplication sharedApplication] keyWindow] addSubview:[CustomerAlert sharedInstance]];
    }
}

+ (void)hideCustomerAlert {
    [CAlert hide];
}

+ (CGFloat)customerAlertMaxWidth {
    return [CustomerAlert subViewWidth];
}

+ (void)showLocalToast:(NSString *)localTitle {
    [Common showToast:[Common getLocalStr:localTitle]];
}

+ (void)showToast:(NSString *)message {
    [Common showToast:message inView:[[UIApplication sharedApplication] keyWindow]];
}

+ (void)showToast:(NSString *)message inView:(UIView*)view {
    static id toastPosition = nil;
    if (!toastPosition) {
        toastPosition = CSToastPositionCenter;
        toastPosition = [NSValue valueWithCGPoint:CGPointMake(ScreenWidth / 2.f,
                                                              ScreenHeight - kToastHeightAboveBottom)];
    }
    
    [view makeToast:message
           duration:2.f
           position:toastPosition];
}

+ (void)hideToast {
    
}

+ (double)folderSizeAtPath:(NSString*) folderPath {
    NSFileManager* fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:folderPath])
        return 0;
    
    NSEnumerator *childFilesEnumerator = [[fm subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [Common fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.f*1024.f);
}

+ (void)analyseNetworkResponseAndNotify:(id)data
                               moduleID:(NSInteger)moduleID
                              funIDSucc:(NSInteger)funIDSucc
                              funIDFail:(NSInteger)funIDFail {
    [Common analyseNetworkResponseAndNotify:(id)data
                                   moduleID:(NSInteger)moduleID
                                  funIDSucc:(NSInteger)funIDSucc
                                  funIDFail:(NSInteger)funIDFail
                                    success:nil
                                    failure:nil];
}

+ (void)analyseNetworkResponseAndNotify:(id)data
                               moduleID:(NSInteger)moduleID
                              funIDSucc:(NSInteger)funIDSucc
                              funIDFail:(NSInteger)funIDFail
                                success:(void (^)(NSDictionary *dic))success
                                failure:(void (^)(NSDictionary *dic))failure {
    NSDictionary *rspDic = data;
    id rspData = [rspDic objectForKey:kNetworkResponseData];
    if ([rspData isKindOfClass:[NSError class]]) {
        [BF broadcastBusinessNotification:(unsigned int)BusinesID(moduleID, funIDFail) inParam:data];
    } else {
        NSError *error = nil;
        /*
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:rspData
                                                            options:NSJSONReadingMutableLeaves
                                                              error:&error];
         */
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:rspData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&error
                                                      removingNulls:YES
                                                       ignoreArrays:NO];
        
        if (!error) {
            NSDictionary *notifyDic = [NSDictionary dictionaryWithObjectsAndKeys:dic, kNetworkResponseData, [rspDic objectForKey:kNetworkRequestInfo], kNetworkRequestInfo, nil];
            LogDebug(@"response notifyDic: %@", notifyDic);
            //若返回的是正确的数据包，则分析
            NSString *resultCode = [dic objectForKey:kNetworkResponseRetcodeKey];
            if (resultCode && resultCode.integerValue == kNetworkResponseRetcodeSucc) {
                if (success) {
                    success(dic);
                }
                //返回成功，提前返回
                [BF broadcastBusinessNotification:(unsigned int)BusinesID(moduleID, funIDSucc) inParam:notifyDic];
                return;
            } else {
                if (resultCode) {
                    if (![Common processByCommonErrorCode:[resultCode integerValue] dic:dic]) {
                        return;
                    }
                }
                
                if (failure) {
                    failure(dic);
                }
                [BF broadcastBusinessNotification:(unsigned int)BusinesID(moduleID, funIDFail) inParam:notifyDic];
            }
        } else {
            [BF broadcastBusinessNotification:(unsigned int)BusinesID(moduleID, funIDFail) inParam:[NSDictionary dictionaryWithObjectsAndKeys:error, kNetworkResponseData, [rspDic objectForKey:kNetworkRequestInfo], kNetworkRequestInfo, nil]];
        }
    }
}

+ (BOOL)processByCommonErrorCode:(NSInteger)errorCode dic:(NSDictionary*)dic {
    switch (errorCode) {
        case NetworkResponseCodeLoginExpired:
        case NetworkResponseCodeAnotherLogined: {
            NSString *message = dic[kNetworkResponseMessageKey];
            UIViewController *viewController = [Common logoutToWindow];
            if (![Common isEmptyString:message]) {
                //[Common showToast:[dic objectForKey:message]];
                [Common showToast:message inView:viewController.view];
            }
            return NO;
            break;
        }
            
        default:
            break;
    }
    return YES;
}

+ (void)updateTableByNewData:(UITableView*)tableView
                  tableArray:(NSMutableArray*)tableArray
                updatedArray:(NSArray*)updatedArray {
    [tableArray removeAllObjects];
    [tableArray addObjectsFromArray:updatedArray];
    [tableView reloadData];
}

+ (NSInteger)updateTableByMoreData:(UITableView*)tableView
                   tableArray:(NSMutableArray*)tableArray
                 updatedArray:(NSArray*)updatedArray
                    uniqueKey:(NSString*)uniqueKey {
    if (updatedArray.count > 0) {
        //此处应该进行更新后去重
        for (NSDictionary *dic in updatedArray) {
            id uniqueId = dic[uniqueKey];
            BOOL isUpdated = NO;
            for (int i = 0; i < tableArray.count; i++) {
                NSDictionary *oldDic = tableArray[i];
                id oldUniqueId = oldDic[uniqueKey];
                if ([uniqueId intValue] == [oldUniqueId intValue]) {
                    //更新已有的数据
                    tableArray[i] = dic;
                    isUpdated = YES;
                    break;
                }
            }
            
            if (!isUpdated) {
                //若是新数据，则添加到dataArr中
                [tableArray addObject:dic];
            }
        }
        [tableView reloadData];
    }
    return updatedArray.count;
}

+ (UIViewController*)logoutToWindow {
    [Common updateToken:@""];
    UIViewController *viewController = [[Common rootViewController] popToViewControllerKindClass:[LoginViewController class]
                                                                                        animated:YES];
    ((LoginViewController*)viewController).passwordTextField.text = nil;
    viewController.navigationController.navigationBarHidden = YES;
    return viewController;
}

+ (NSMutableDictionary*)getNavigationBarBtnFullSetting {
    NSMutableDictionary *setting = [NSMutableDictionary dictionary];
    [setting setObject:@"" forKey:kNavigationBarBtnStyleKey];
    [setting setObject:@"" forKey:kNavigationBarBtnTitleKey];
    
    NSMutableDictionary *images = [NSMutableDictionary dictionary];
    [images setObject:@"" forKey:kNavigationBarBtnBackgroundImagesNormalKey];   //此处Object设置成UIImage*
    [images setObject:@"" forKey:kNavigationBarBtnBackgroundImagesClickedKey];  //此处Object设置成UIImage*
    [setting setObject:images forKey:kNavigationBarBtnBackgroundImagesKey];
    
    [setting setObject:@"" forKey:kNavigationBarBtnTargetKey];  //此处Object设置成ViewController的指针
    [setting setObject:@"" forKey:kNavigationBarBtnActionKey];  //此处Object设置成 [NSValue valueWithBytes:&selector objCType:@encode(SEL)];
    
    return setting;
}

+ (void)setNavigationBarBtn:(id)setting
                   inButton:(UIBarButtonItem*)inButton
                  outButton:(UIBarButtonItem**)outButton {
    if ([setting isKindOfClass:[NSString class]]) {
        inButton.title = setting;
    } else if ([setting isKindOfClass:[UIImage class]]) {
        [inButton setImage:setting];
    } else if ([setting isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = setting;
        NSString *style = [dic objectForKey:kNavigationBarBtnStyleKey];
        NSString *title = [dic objectForKey:kNavigationBarBtnTitleKey];
        id bgImages = [dic objectForKey:kNavigationBarBtnBackgroundImagesKey];
        id target = [dic objectForKey:kNavigationBarBtnTargetKey];
        id selector = [dic objectForKey:kNavigationBarBtnActionKey];
        NSValue *actionValue = nil;
        if (![selector isKindOfClass:[NSString class]]) {
            actionValue = selector;
        }
        
        UIBarButtonItem *buttonItem = nil;
        //如果需要自定义点击事件，则需要重新生成按钮
        if (actionValue) {
            SEL action;
            [actionValue getValue:&action];
            
            buttonItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:target action:action];
            *outButton = buttonItem;
        } else {
            buttonItem = inButton;
        }
        
        if ([style isEqualToString:kNavigationBarBtnStyleText]) {
            buttonItem.title = title;
        } else if ([style isEqualToString:kNavigationBarBtnStyleImage]) {
            NSDictionary *dic = [Common setNavaigationBarBtnBgImages:bgImages];
            UIImageView *normal = [dic objectForKey:kNavigationBarBtnBackgroundImagesNormalKey];
            if (normal) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                if (actionValue) {
                    SEL action;
                    [actionValue getValue:&action];
                    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
                }
                button.frame = MakeRect(0, 0, ViewWidth(normal), ViewHeight(normal));
                //button.frame = normal.frame;
                [button setImage:normal.image forState:UIControlStateNormal];
                UIImageView *clicked = [dic objectForKey:kNavigationBarBtnBackgroundImagesClickedKey];
                [button setImage:clicked.image forState:UIControlStateHighlighted];
                buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
                *outButton = buttonItem;
            }
        } else if ([style isEqualToString:kNavigationBarBtnStyleTextImage]) {
            buttonItem.title = title;
            NSDictionary *dic = [Common setNavaigationBarBtnBgImages:bgImages];
            UIImageView *normal = [dic objectForKey:kNavigationBarBtnBackgroundImagesNormalKey];
            if (normal) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                if (actionValue) {
                    SEL action;
                    [actionValue getValue:&action];
                    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
                }
                button.frame = MakeRect(0, 0, ViewWidth(normal), ViewHeight(normal));
                //button.frame = normal.frame;
                [button setImage:normal.image forState:UIControlStateNormal];
                [button setBackgroundImage:normal.image forState:UIControlStateNormal];
                UIImageView *clicked = [dic objectForKey:kNavigationBarBtnBackgroundImagesClickedKey];
                [button setBackgroundImage:clicked.image forState:UIControlStateHighlighted];
                buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
                buttonItem.title = title;
                *outButton = buttonItem;
            }
        }
    }
}

+ (NSDictionary*)setNavaigationBarBtnBgImages:(id)images {
    if (!images) {
        return nil;
    }
    
    NSMutableDictionary *retDic = [NSMutableDictionary dictionary];
    UIImageView *normal = nil;
    UIImageView *clicked = nil;
    if ([images isKindOfClass:[UIImageView class]]) {
        [retDic setValue:images forKey:kNavigationBarBtnBackgroundImagesNormalKey];
        //做图像处理
        //clicked = [normal gaussianBlurWithBias:0];
    } else if ([images isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = images;
        normal = [dic objectForKey:kNavigationBarBtnBackgroundImagesNormalKey];
        clicked = [dic objectForKey:kNavigationBarBtnBackgroundImagesClickedKey];
        if ([normal isKindOfClass:[UIImageView class]]) {
            [retDic setValue:normal forKey:kNavigationBarBtnBackgroundImagesNormalKey];
            if ([clicked isKindOfClass:[UIImageView class]]) {
                [retDic setValue:clicked forKey:kNavigationBarBtnBackgroundImagesClickedKey];
            }
        }
    }
    
    return retDic;
}

//年
+ (NSString*)yearUnit {
    static NSString *yearUnit;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        yearUnit = [Common getLocalStr:@"YearUnit"];
    });
    
    return yearUnit;
}

//万
+ (NSString*)tenThousandUnit {
    static NSString *tenThousandUnit;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        tenThousandUnit = [Common getLocalStr:@"TenThousandUnit"];
    });
    
    return tenThousandUnit;
}

//公里
+ (NSString*)kilometreUnit {
    static NSString *kilometreUnit;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        kilometreUnit = [Common getLocalStr:@"KilometreUnit"];
    });
    
    return kilometreUnit;
}

//里程，万公里
+ (NSString*)mileageUnit {
    static NSString *mileageUnit;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        mileageUnit = [Common getLocalStr:@"MileageUnit"];
    });
    
    return mileageUnit;
}

+ (NSString *)countNumAndChangeformat:(NSString *)num {
    int count = 0;
    long long int a = num.longLongValue;
    while (a != 0) {
        count++;
        a /= 10;
    }
    
    NSMutableString *string = [NSMutableString stringWithString:num];
    NSArray *arr = [num componentsSeparatedByString:@"."];
    if (arr.count > 1) {
        string = [NSMutableString stringWithString:[arr objectAtIndex:0]];
    }
    
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [newstring insertString:string atIndex:0];
    
    //补充浮点数的位数
    if (arr.count > 1) {
        [newstring appendString:@"."];
        [newstring appendString:[arr objectAtIndex:1]];
    }
    return newstring;
}

+ (NSString*)numberWithTenThousand:(float)number {
    if (number < 10000.f) {
        return [NSString stringWithFormat:@"%ld", (long)number];
    }
    
    //格式化输出
    NSInteger intValue = number / 10000;
    NSString *str;
    if (number == intValue * 10000) {
        str = [NSString stringWithFormat:@"%ld%@", (long)intValue, [Common tenThousandUnit]];
    } else {
        str = [NSString stringWithFormat:@"%.1f%@", number / 10000.f, [Common tenThousandUnit]];
        if (number != str.floatValue * 10000.f) {
            str = [NSString stringWithFormat:@"%.2f%@", number / 10000.f, [Common tenThousandUnit]];
        }
    }
    return str;
}

+ (NSString*)normalNumToBankNum:(NSString*)normalNum {
    NSString *str = [Common bankNumToNormalNum:normalNum];
    NSInteger size = (str.length / 4);
    NSMutableArray *strArr = [[NSMutableArray alloc] init];
    for (int i = 0;i < size; i++) {
        [strArr addObject:[str substringWithRange:NSMakeRange(i * kBankCardNoGroupLength,
                                                                    kBankCardNoGroupLength)]];
    }
    
    [strArr addObject:[str substringWithRange:NSMakeRange(size * kBankCardNoGroupLength,
                                                                (str.length % kBankCardNoGroupLength))]];
    return [strArr componentsJoinedByString:@" "];
}

+ (NSString*)bankNumToNormalNum:(NSString*)bankNum {
    return [bankNum stringByReplacingOccurrencesOfString:@" " withString:@""];
}

+ (NSArray *)chinaRegion {
    NSArray *provinceArr = [NSJSONSerialization JSONObjectWithData:[FileIO getFileAtPath:kConfigFileProvinceList]
                                                           options:NSJSONReadingMutableContainers
                                                             error:nil
                                                     removingNulls:YES
                                                      ignoreArrays:NO];
    NSArray *cityArr = [NSJSONSerialization JSONObjectWithData:[FileIO getFileAtPath:kConfigFileCityList]
                                                       options:NSJSONReadingMutableContainers
                                                         error:nil
                                                 removingNulls:YES
                                                  ignoreArrays:NO];
    NSArray *regionArr = [NSJSONSerialization JSONObjectWithData:[FileIO getFileAtPath:kConfigFileRegionList]
                                                       options:NSJSONReadingMutableContainers
                                                         error:nil
                                                 removingNulls:YES
                                                  ignoreArrays:NO];
    NSMutableArray *arr = [NSMutableArray array];
    for (NSDictionary *province in provinceArr) {
        NSMutableDictionary *provinceFull = [NSMutableDictionary dictionaryWithDictionary:province];
        NSMutableArray *cityFullArr = [NSMutableArray array];
        for (NSDictionary *city in cityArr) {
            if ([city[kConfigKeyPid] intValue] == [province[kCommonParamId] intValue]) {
                NSMutableDictionary *cityFull = [NSMutableDictionary dictionaryWithDictionary:city];
                NSMutableArray *regionFullArr = [NSMutableArray array];
                [cityFullArr addObject:cityFull];
                for (NSDictionary *region in regionArr) {
                    if ([region[kConfigKeyPid] intValue] == [city[kCommonParamId] intValue]) {
                        [regionFullArr addObject:[NSDictionary dictionaryWithDictionary:region]];
                    }
                }
                cityFull[kConfigKeyRegion] = [NSArray arrayWithArray:regionFullArr];
            }
        }
        provinceFull[kConfigKeyCity] = [NSArray arrayWithArray:cityFullArr];
        [arr addObject:[NSDictionary dictionaryWithDictionary:provinceFull]];
    }
    return [NSArray arrayWithArray:arr];
}

+ (NSArray *)getChindRegionIndexs:(NSArray *)chinaRegionArr
                            pName:(NSString *)pName
                            cName:(NSString *)cName
                            rName:(NSString *)rName {
    NSMutableArray *arr = [NSMutableArray arrayWithArray:@[@(0), @(0), @(0)]];
    if (pName && pName.length > 0) {
        for (int i = 0; i < chinaRegionArr.count; i++) {
            NSDictionary *province = chinaRegionArr[i];
            if ([pName isEqualToString:province[kCommonParamName]]) {
                arr[0] = @(i);
                NSArray *cityArr = province[kConfigKeyCity];
                if (cName && cName.length > 0) {
                    for (int j = 0; j < cityArr.count; j++) {
                        NSDictionary *city = cityArr[j];
                        if ([cName isEqualToString:city[kCommonParamName]]) {
                            arr[1] = @(j);
                            NSArray *regionArr = city[kConfigKeyRegion];
                            if (rName && rName.length > 0) {
                                for (int k = 0; k < regionArr.count; k++) {
                                    NSDictionary *region = regionArr[k];
                                    if ([rName isEqualToString:region[kCommonParamName]]) {
                                        arr[2] = @(k);
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                break;
            }
        }
    }
    return [NSArray arrayWithArray:arr];
}

+ (NSArray *)getChinaRegion:(NSArray *)chinaRegionArr
                       pIndex:(NSInteger)pIndex
                       cIndex:(NSInteger)cIndex
                       rIndex:(NSInteger)rIndex {
    NSMutableArray *arr = [NSMutableArray array];
    if (pIndex < chinaRegionArr.count) {
        NSDictionary *province = chinaRegionArr[pIndex];
        BOOL enable = province && [province isKindOfClass:[NSDictionary class]];
        if (!enable) {
            return arr;
        }
        [arr addObject:province];
        NSArray *cityArr = enable ? province[kConfigKeyCity] : nil ;
        if (cityArr && [cityArr isKindOfClass:[NSArray class]] && cIndex < cityArr.count) {
            NSDictionary *city = cityArr[cIndex];
            BOOL enable = city && [city isKindOfClass:[NSDictionary class]];
            if (!enable) {
                return arr;
            }
            [arr addObject:city];
            NSArray *regionArr = enable ? city[kConfigKeyRegion] : nil;
            if (regionArr && [regionArr isKindOfClass:[NSArray class]] && rIndex < regionArr.count) {
                NSDictionary *region = regionArr[rIndex];
                if (region && [region isKindOfClass:[NSDictionary class]]) {
                    [arr addObject:region];
                }
            }
        }
    }
    return [NSArray arrayWithArray:arr];
}

+ (NSArray *)getChindRegionID:(NSArray *)chinaRegionArr
                        pName:(NSString *)pName
                        cName:(NSString *)cName
                        rName:(NSString *)rName{
    NSMutableArray *arr = [NSMutableArray arrayWithArray:@[@(0), @(0), @(0)]];
    if (pName && pName.length > 0) {
        for (int i = 0; i < chinaRegionArr.count; i++) {
            NSDictionary *province = chinaRegionArr[i];
            if ([pName isEqualToString:province[kCommonParamName]]) {
                arr[0] = @([province[kCommonParamId] integerValue]);
                NSArray *cityArr = province[kConfigKeyCity];
                if (cName && cName.length > 0) {
                    for (int j = 0; j < cityArr.count; j++) {
                        NSDictionary *city = cityArr[j];
                        if ([cName isEqualToString:city[kCommonParamName]]) {
                            arr[1] = @([city[kCommonParamId] integerValue]);
                            NSArray *regionArr = city[kConfigKeyRegion];
                            if (rName && rName.length > 0) {
                                for (int k = 0; k < regionArr.count; k++) {
                                    NSDictionary *region = regionArr[k];
                                    if ([rName isEqualToString:region[kCommonParamName]]) {
                                        arr[2] = @([region[kCommonParamId] integerValue]);
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                break;
            }
        }
    }
    return [NSArray arrayWithArray:arr];
}
//- (NSArray *)getRegion:(NSInteger)index {
//    NSDictionary *dic = _currentPropertyDic[@(row)];
//    NSString *fileCurrentPath = dic[kPropertyDicKeyFieldCurrentPath];
//    NSInteger pIndex = 0;
//    NSInteger cIndex = 0;
//    NSArray *component = [fileCurrentPath componentsSeparatedByString:@","];
//    pIndex = component.count > 0 ? [component[0] integerValue] : pIndex;
//    cIndex = component.count > 1 ? [component[1] integerValue] : cIndex;
//    return [self getProvince:pIndex city:cIndex];
//}

+ (NSString *)getChinaProvince:(NSArray *)chinaRegionArr index:(NSInteger)index {
    if (index < chinaRegionArr.count) {
        NSDictionary *province = chinaRegionArr[index];
        return province && [province isKindOfClass:[NSDictionary class]] ? province[kCommonParamName] : kEmptyString;
    }
    return @"";
}

+ (NSArray *)getChinaProvince:(NSArray *)chinaRegionArr pIndex:(NSInteger)pIndex cIndex:(NSInteger)cIndex {
    NSString *provinceName = @"";
    NSString *cityName = @"";
    if (pIndex < chinaRegionArr.count) {
        NSDictionary *province = chinaRegionArr[pIndex];
        BOOL enable = province && [province isKindOfClass:[NSDictionary class]];
        provinceName = enable ? province[kCommonParamName] : kEmptyString;
        NSArray *cityArr = enable ? province[kConfigKeyCity] : nil ;
        if (cityArr && [cityArr isKindOfClass:[NSArray class]] && cIndex < cityArr.count) {
            NSDictionary *city = cityArr[cIndex];
            cityName = city[kCommonParamName];
        }
    }
    return @[provinceName, cityName];
}

+ (NSArray *)getChinaProvince:(NSArray *)chinaRegionArr
                       pIndex:(NSInteger)pIndex
                       cIndex:(NSInteger)cIndex
                       rIndex:(NSInteger)rIndex {
    NSString *provinceName = @"";
    NSString *cityName = @"";
    NSString *regionName = @"";
    if (pIndex < chinaRegionArr.count) {
        NSDictionary *province = chinaRegionArr[pIndex];
        BOOL enable = province && [province isKindOfClass:[NSDictionary class]];
        provinceName = enable ? province[kCommonParamName] : kEmptyString;
        NSArray *cityArr = enable ? province[kConfigKeyCity] : nil ;
        if (cityArr && [cityArr isKindOfClass:[NSArray class]] && cIndex < cityArr.count) {
            NSDictionary *city = cityArr[cIndex];
            BOOL enable = city && [city isKindOfClass:[NSDictionary class]];
            cityName = enable ? city[kCommonParamName] : kEmptyString;
            NSArray *regionArr = enable ? city[kConfigKeyRegion] : nil;
            if (regionArr && [regionArr isKindOfClass:[NSArray class]] && rIndex < regionArr.count) {
                NSDictionary *region = regionArr[rIndex];
                regionName = region && [region isKindOfClass:[NSDictionary class]] ? region[kCommonParamName] : kEmptyString;
            }
        }
    }
    return @[provinceName, cityName, regionName];
}

+(UIColor *)getColor:(NSString *)hexColor

{
    unsigned int red, green, blue;
    NSRange range;
    range.length =2;
    range.location =0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&red];
    range.location =2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&green];
    range.location =4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red/255.0f)green:(float)(green/255.0f)blue:(float)(blue/255.0f)alpha:1.0f];
}
@end
